#!/bin/bash
# ===========================================================================
# 功能: 自动检测并安装Python环境与speedtest-cli以测试服务器网络速度
# 作者: x
# 时间: 2024-06-13
# 注意: 脚本需以root权限执行
# 使用方式: curl http://javatt.top:9000/sdkj/sh/testspeed.sh | sh
# ===========================================================================

# 检查是否为root用户
check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        echo "请使用root权限运行此脚本"
        exit 1
    fi
}
check_root

# 系统类型检测及包管理器设定
detect_system() {
    if command -v lsb_release &> /dev/null; then
        OS_DISTRO=$(lsb_release -is)
        case $OS_DISTRO in
            Ubuntu|Debian)
                PACKAGE_MANAGER="apt-get"
                PYTHON_PACKAGE="python3"
                PIP_PACKAGE="python3-pip"
                ;;
            CentOS|RedHatEnterpriseServer)
                PACKAGE_MANAGER="yum"
                PYTHON_PACKAGE="python36"
                PIP_PACKAGE="python36-pip"
                ;;
            *)
                echo "当前系统(${OS_DISTRO})不支持自动配置，请手动安装Python 3和pip后运行speedtest-cli。"
                exit 1
                ;;
        esac
    else
        echo "无法识别系统类型，无法继续。"
        exit 1
    fi
}

# 安装Python 3
install_python() {
    echo "正在安装Python 3..."
    ${PACKAGE_MANAGER} update && ${PACKAGE_MANAGER} install -y ${PYTHON_PACKAGE}
    # 特定情况软链接修正
    if [[ "${OS_DISTRO}" == "CentOS" || "${OS_DISTRO}" == "RedHatEnterpriseServer" ]]; then
        ln -sf /usr/bin/python3.6 /usr/bin/python3 2>/dev/null || true
    fi
}

# 安装pip3
install_pip() {
    echo "正在安装pip3..."
    ${PACKAGE_MANAGER} install -y ${PIP_PACKAGE}
}

# 安装speedtest-cli
install_speedtest_cli() {
    echo "正在安装speedtest-cli..."
    pip3 install --upgrade speedtest-cli
}

# 执行网络速度测试
run_speedtest() {
    echo "正在进行网络速度测试..."
    speedtest-cli
}




# 主程序逻辑
if command -v speedtest-cli &> /dev/null; then
    run_speedtest
else
   detect_system
    if ! command -v python3 &> /dev/null; then
        install_python
    fi
    if ! command -v pip3 &> /dev/null; then
        install_pip
    fi
    install_speedtest_cli
    run_speedtest
fi
